package com.ducanh.doan.database;

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.ducanh.doan.database.model.User;

public class DBAdapter extends SQLiteHelper {

	public DBAdapter(Context context) {
		super(context);
	}
	
	public boolean addUser(String name) {
		try {
			SQLiteDatabase db = getWritableDatabase();
			db.execSQL("INSERT INTO "+TABLE_USER+"(name) VALUES(?)", new String[] { name });
			db.close();
			return true;
		} catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public User getUser(int userId) {
		User user = new User();
		SQLiteDatabase db = getReadableDatabase();
		if (db != null) {
			Cursor c = db.query(TABLE_USER, new String[] { KEY_USER_ID, KEY_USER_NAME, KEY_USER_ORDER, KEY_USER_DESCRIPTION }, " id="+userId, null, null, null, null);
			if (c.moveToFirst()) {
				user.setName(c.getString(c.getColumnIndex(KEY_USER_NAME)));
				user.setUserId(c.getInt(c.getColumnIndex(KEY_USER_ID)));
				user.setDescription(c.getString(c.getColumnIndex(KEY_USER_DESCRIPTION)));
				user.setOrderNo(c.getInt(c.getColumnIndex(KEY_USER_ORDER)));
			}
			db.close();
		}
		return user;
	}
	
	public ArrayList<User> getAllUsers() {
		SQLiteDatabase db = getReadableDatabase();
		ArrayList<User> data = new ArrayList<User>();
		if (db != null) {
			Cursor c = db.query(TABLE_USER, new String[] { KEY_USER_ID, KEY_USER_NAME, KEY_USER_ORDER, KEY_USER_DESCRIPTION }, null, null, null, null, null);
			if (c.moveToFirst()) {
				do {
					User user = new User();
					user.setName(c.getString(c.getColumnIndex(KEY_USER_NAME)));
					user.setUserId(c.getInt(c.getColumnIndex(KEY_USER_ID)));
					user.setDescription(c.getString(c.getColumnIndex(KEY_USER_DESCRIPTION)));
					user.setOrderNo(c.getInt(c.getColumnIndex(KEY_USER_ORDER)));
					data.add(user);
				} while(c.moveToNext());
			}
			db.close();
		}
		return data;
	}

}
